const path = require('path')
const Compiler = require('./Compiler')
const { logInfo, logStep } = require('../../util/logInfo')

const getNormalizedWebpackOptions = (rawOptions) => {
    return {
        context: path.resolve(__dirname, 'src')
    }
}


const createMultiComplier = () => {

}

const createCompiler = (rawOptions) => {
    logStep('creat complier')
    logInfo('用户配置+默认配置，组合成格式化的配置。')
    const options = getNormalizedWebpackOptions(rawOptions)
    const compiler = new Compiler(options.context);
    compiler.options = options;

    return compiler;
}



const webpack = (options, callback) => {
    options = options || {};
    const create = () => {
        logStep('开始创建编译器 compiler')
        let compiler;
        let watch = false;
        let watchOptions;
        if (Array.isArray(options)) {
            logInfo('多个配置，可以创建基于多个配置的编译器，但是 watch 只能有一个')
            compiler = createMultiComplier(options, options);
            watch = options.some(option => option.watch);
            watchOptions = options.map(option => option.watchOptions || {});
        } else {
            logInfo('创建单个配置的编译器，通常也是用的这个。')
            const webpackOptions = options;
            complier = createCompiler(webpackOptions);
            watch = webpackOptions.watch;
            watchOptions = webpackOptions.watchOptions;
        }
        return { complier, watch, watchOptions }
    }

    if (callback) {
        try {
            const { complier, watch, watchOptions } = create();
            if (watch) {
                logStep('compiler.watch 开始执行编译流程。')
                complier.watch(watchOptions, callback);
            } else {
                logStep('compiler.run 开始执行编译流程。')
                complier.run((err, stats) => {
                    complier.close(err2 => {
                        callback(err || err2, stats);
                    })
                })
            }
            return complier;
        } catch (error) {
            console.log(error);
            process.nextTick(() => callback(error));
        }
    } else {
        const { compiler, watch } = create();
        if (watch) {

        }
    }
}

module.exports = webpack;